package cmd

import (
	"fmt"
	"io/ioutil"
	"os"

	"gitee.com/xuender/toolkit/format"
	"github.com/spf13/cobra"
)

func toJSON(f, indent string, cover bool) error {
	bs, err := ioutil.ReadFile(f)
	if err != nil {
		return err
	}

	bs, err = format.JSONBytes(bs, indent)
	if err != nil {
		return err
	}

	if cover {
		info, err := os.Stat(f)
		if err != nil {
			return err
		}

		return ioutil.WriteFile(f, bs, info.Mode())
	}

	fmt.Fprintf(os.Stdout, "%s\n", bs)

	return nil
}

// nolint: gochecknoinits
func init() {
	jsonCmd := &cobra.Command{
		Use:   "json",
		Short: "Json 格式化",
		Long:  `Json 文件格式化`,
		Run: func(cmd *cobra.Command, args []string) {
			indent, _ := cmd.Flags().GetString("indent")
			if len(args) == 0 {
				bs, err := ioutil.ReadAll(os.Stdin)
				if err == nil {
					bs, err = format.JSONBytes(bs, indent)
					if err == nil {
						fmt.Fprintf(os.Stdout, "%s\n", string(bs))

						return
					}
				}

				fmt.Fprintf(os.Stdout, "%s\n", err)

				return
			}

			cover, _ := cmd.Flags().GetBool("cover")

			for _, f := range args {
				if err := toJSON(f, indent, cover); err != nil {
					fmt.Fprintf(os.Stdout, "%s  %s\n", err, f)
				}
			}
		},
	}

	rootCmd.AddCommand(jsonCmd)
	jsonCmd.Flags().StringP("indent", "i", "\t", "缩进")
	jsonCmd.Flags().BoolP("cover", "c", false, "覆盖原有文件")
}
